package cn.stylefeng.guns.modular.fsjs.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.ExcellUtil;
import cn.stylefeng.guns.core.util.ServerResponse;
import cn.stylefeng.guns.modular.system.model.Indenteruwy;
import cn.stylefeng.guns.modular.system.model.Swyreport;
import cn.stylefeng.guns.modular.system.model.Techchange;
import cn.stylefeng.guns.modular.system.model.User;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.dao.SwyreportMapper;
import cn.stylefeng.guns.modular.system.dao.TechchangeMapper;
import cn.stylefeng.guns.modular.fsjs.service.ITechchangeService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2019-03-06
 */
@Service
public class TechchangeServiceImpl extends ServiceImpl<TechchangeMapper, Techchange> implements ITechchangeService {
	String mainPath="";
	@Autowired
	private TechchangeMapper techchangeMapper;
	@Autowired
    private IUserService userService;
	@Override
	@Transactional(propagation =Propagation.REQUIRED,rollbackFor=Exception.class,isolation = Isolation.READ_COMMITTED)
	public Object pushMsg(HttpServletRequest request, List<Techchange> techchangeLi) {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    	User user = userService.selectById(ShiroKit.getUser().getId());
    	if(techchangeMapper.getIfComit(user)>0){
			return ServerResponse.createByErrorMessage("年报数据已经提交，无法修改");
		}
    	mainPath=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\";
    	int point=0;
		
    	for(int i=0;i<techchangeLi.size();i++){
			Techchange temp=techchangeLi.get(i);
			if(this.checkInput(temp, i)==false){
				return ServerResponse.createByErrorMessage("提交数据有误");
			}
    	}
    	
    	for(int i=0;i<techchangeLi.size();i++){
			Techchange temp=techchangeLi.get(i);
			if(this.checkInput(temp, i)==true){
				temp.setAccount(user.getAccount());
				temp.setOperater(user.getAccount());
				temp.setVersion("2");
				temp.setTs(sf.format(new Date()));
			}else{
				continue;
			}
			if(i==0){
				techchangeMapper.delTempMsg(temp);
			}
			
			if(techchangeMapper.pushMsg(temp)==0){
				return ServerResponse.createByErrorMessage("保存数据库出错");
			}else if(i==0){
				point++;
			}
			
		}
//			this.delMsg(user);
			if(point>0){
				//初始化excell成功
				Techchange temp=techchangeLi.get(0);
				temp.setAccount(user.getAccount());
				ServerResponse cf=(ServerResponse)this.createFile(temp);
				if(cf.getCode()==200){
					//
					List<Techchange> bsg=this.getMsgByAccountExcell(temp);
					if(bsg.size()>0){
						if(bsg.size()>3){
							for(int j=0;j<bsg.size()-3;j++){
								ExcellUtil.insertRows(mainPath+temp.getAccount()+"_技改年报.xlsx", 13+j, 25, 21,10);
							}
						}
						ServerResponse sm=(ServerResponse)this.stuffMsg(bsg,user);
						if(sm.getCode()==200){
							ServerResponse fn=(ServerResponse)this.toPDF(temp);
							if(fn.getCode()==200){
								this.delMsg(user);
								return ServerResponse.createBySuccessMessage("保存成功");
							}else{
								return fn;
							}
						}else{
							return sm;
						}
						
					}else{
						return ServerResponse.createByErrorMessage("数据库不存在记录");
					}
					
				}else{
					return cf;
				}
				
			}else{
				return ServerResponse.createByErrorMessage("数据格式错误");
			}
		
	}

	public boolean checkInput(Techchange temp,int i){
		if(temp.getRecYear()!=null&&
//				   temp.getManagement()!=null&&
				   StringUtils.isNotBlank(temp.getUnitName())&&
				   StringUtils.isNotBlank(temp.getPrjName())&&
				   StringUtils.isNotBlank(temp.getUseType())&&
				   StringUtils.isNotBlank(temp.getPrjType())&&
				   StringUtils.isNotBlank(temp.getPrjPlace())&&
				   StringUtils.isNotBlank(temp.getStarTime())&&
				   StringUtils.isNotBlank(temp.getEndTime())&&
				   StringUtils.isNotBlank(temp.getPrjStatus())&&
				   temp.getSumFund()!=null&&
				   temp.getOtherScale()!=null&&
				   temp.getSumSave()!=null&&
				   temp.getUnitHead()!=null){
					return true;
				}else{
					return false;
				}
	}
	
	@Override
	public List<Techchange> getMsgByAccount(User user) {
		return techchangeMapper.getMsgByAccount(user);
	}

	@Override
	public List<Map<String, String>> getHangyeCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Techchange> getMsgByAccountExcell(Techchange techchange) {
		
		/*File file=new File(mainPath+swyreport.getAccount()+"_用水单位基本信息.xlsx");
		 FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			Workbook workbook= WorkbookFactory.create(fis);
			Sheet sheet=workbook.getSheetAt(0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return techchangeMapper.getMsgByAccountExcell(techchange);
	}

	
	
	private Object createFile(Techchange techchange){
		return ExcellUtil.copyFile(mainPath,techchange,"技改年报");
	}
	
	private Object stuffMsg(List<Techchange> techchangeLi,User user){
//		ExcellUtil.insertRows(mainPath+swyreport.getAccount()+"_中水.xlsx", 12,30,16);
		File file=new File(mainPath+techchangeLi.get(0).getAccount()+"_技改年报.xlsx");
		try {
		FileInputStream fis=new FileInputStream(file);
	     Workbook workbook= WorkbookFactory.create(fis);
	     Sheet sheet=workbook.getSheetAt(0);
	     int size=3;
	     if(techchangeLi.size()>3){
	    	 size=techchangeLi.size();
	     }
	   //填表单位名称
	     if(StringUtils.isNotBlank(user.getCompany())){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,0,5);
	    	 oldValue=oldValue.replace("：", "："+user.getCompany());
	    	 ExcellUtil.updateExcel(sheet,0,5,oldValue);
	     }
	   //年份
	     if(techchangeLi.get(0).getRecYear()!=null){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,4,5);
	    	 oldValue=oldValue.replace("20  ", Integer.toString(techchangeLi.get(0).getRecYear()));
	    	 ExcellUtil.updateExcel(sheet,4,5,oldValue);
	     }
		//报出日期
		 if(StringUtils.isNotBlank(techchangeLi.get(0).getTs())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,10+size);
	    	 oldValue=oldValue.replace("20", techchangeLi.get(0).getTs().substring(0, 4));
	    	 oldValue=oldValue.replace("月", techchangeLi.get(0).getTs().substring(5, 7)+"月");
	    	 oldValue=oldValue.replace("日 ", techchangeLi.get(0).getTs().substring(8, 10)+"日");
			 ExcellUtil.updateExcel(sheet,0,10+size,oldValue);
		 }
		 //统计负责人： 
		 if(StringUtils.isNotBlank(techchangeLi.get(0).getUnitHead())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,10+size);
			 String preValue="";
			 for(int c=0;c<techchangeLi.get(0).getUnitHead().length();c++){
				 preValue=preValue+" ";
			 }
			 oldValue=oldValue.replace("单位负责人： "+preValue, "单位负责人： "+techchangeLi.get(0).getUnitHead());
			 ExcellUtil.updateExcel(sheet,0,10+size,oldValue);
		 }
		 //填表人
		 if(StringUtils.isNotBlank(techchangeLi.get(0).getOperater())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,10+size);
			 String preValue="";
			 for(int c=0;c<techchangeLi.get(0).getOperater().length();c++){
				 preValue=preValue+" ";
			 }
			 oldValue=oldValue.replace("填表人："+preValue, "填表人："+techchangeLi.get(0).getOperater());
			 ExcellUtil.updateExcel(sheet,0,10+size,oldValue);
		 }
		 //电话
		 if(StringUtils.isNotBlank(user.getPhone())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,10+size);
			 String preValue="";
			 for(int c=0;c<user.getPhone().length();c++){
				 preValue=preValue+" ";
			 }
			 oldValue=oldValue.replace("电话："+preValue, "电话："+user.getPhone());
			 ExcellUtil.updateExcel(sheet,0,10+size,oldValue);
		 }
	     
		for(int i=0;i<techchangeLi.size();i++){
			Techchange tmp=techchangeLi.get(i);
			//所属节水管理部门
			/*if(StringUtils.isNotBlank(tmp.getManagement())){
				ExcellUtil.updateExcel(sheet,0,10+i,tmp.getManagement());
			}*/
			//用水户名
			if(StringUtils.isNotBlank(tmp.getUnitName())){
				ExcellUtil.updateExcel(sheet,2,10+i,tmp.getUnitName());
			}
			//项目名称
			if(StringUtils.isNotBlank(tmp.getPrjName())){
				ExcellUtil.updateExcel(sheet,1,10+i,tmp.getPrjName());
			}
			//所属节水管理部门
			if(StringUtils.isNotBlank(tmp.getManagement())){
				ExcellUtil.updateExcel(sheet,0,10+i,tmp.getManagement());
			}
			//取水用途
			if(StringUtils.isNotBlank(tmp.getUseType())){
				ExcellUtil.updateExcel(sheet,3,10+i,tmp.getUseType());
			}
			//项目类型
			if(StringUtils.isNotBlank(tmp.getPrjType())){
				ExcellUtil.updateExcel(sheet,4,10+i,tmp.getPrjType());
			}
			//建设地址
			if(StringUtils.isNotBlank(tmp.getPrjPlace())){
				ExcellUtil.updateExcel(sheet,5,10+i,tmp.getPrjPlace());
			}
			//开工时间
			if(StringUtils.isNotBlank(tmp.getStarTime())){
				ExcellUtil.updateExcel(sheet,6,10+i,tmp.getStarTime());
			}
			//竣工时间
			if(StringUtils.isNotBlank(tmp.getEndTime())){
				ExcellUtil.updateExcel(sheet,7,10+i,tmp.getEndTime());
			}
			//建设情况	
			if(StringUtils.isNotBlank(tmp.getPrjStatus())){
				ExcellUtil.updateExcel(sheet,8,10+i,tmp.getPrjStatus());
			}
			//合计
			if(tmp.getSumFund()!=null){
//				String temp=Double.toString(tmp.getSubsidyFund()+tmp.getSelfFund()+tmp.getOtherFund());
//				ExcellUtil.updateExcel(sheet,9,10+i,temp);
				ExcellUtil.updateExcel(sheet,9,10+i,Double.toString(tmp.getSumFund()));
			}
			//补助资金	
			if(tmp.getSubsidyFund()!=null){
				ExcellUtil.updateExcel(sheet,10,10+i,Double.toString(tmp.getSubsidyFund()));
			}
			//自筹资金	
			if(tmp.getSelfFund()!=null){
				ExcellUtil.updateExcel(sheet,11,10+i,Double.toString(tmp.getSelfFund()));
			}
			//其他资金	
			if(tmp.getOtherFund()!=null){
				ExcellUtil.updateExcel(sheet,12,10+i,Double.toString(tmp.getOtherFund()));
			}
			//总投资	
			if(tmp.getSumFund()!=null){
				ExcellUtil.updateExcel(sheet,11,10+i,Double.toString(tmp.getSumFund()));
			}
			//其他规模	
			if(tmp.getOtherScale()!=null){
				ExcellUtil.updateExcel(sheet,13,10+i,Double.toString(tmp.getOtherScale()));
			}
			//蓄水池	
			if(tmp.getReservoirVolume()!=null){
				ExcellUtil.updateExcel(sheet,14,10+i,Double.toString(tmp.getReservoirVolume()));
			}
			//透水砖	
			if(tmp.getBrickArea()!=null){
				ExcellUtil.updateExcel(sheet,15,10+i,Double.toString(tmp.getBrickArea()));
			}
			//下凹式绿地	
			if(tmp.getGreenlandArea()!=null){
				ExcellUtil.updateExcel(sheet,16,10+i,Double.toString(tmp.getGreenlandArea()));
			}
			//年节水量	
			if(tmp.getSumSave()!=null){
//				ExcellUtil.updateExcel(sheet,17,10+i,Double.toString(tmp.getSupplyWater()+tmp.getSelfProvide()+tmp.getSurfaceWater()));
				ExcellUtil.updateExcel(sheet,17,10+i,Double.toString(tmp.getSumSave()));
			}
			//自来水	
			if(tmp.getSupplyWater()!=null){
				ExcellUtil.updateExcel(sheet,18,10+i,Double.toString(tmp.getSupplyWater()));
			}
			//自备水	
			if(tmp.getSelfProvide()!=null){
				ExcellUtil.updateExcel(sheet,19,10+i,Double.toString(tmp.getSelfProvide()));
			}
			//地表水	
			if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,20,10+i,Double.toString(tmp.getSurfaceWater()));
			}
			
		}
		fis.close();//关闭文件输入流
		 
	     FileOutputStream fos=new FileOutputStream(file);
	     workbook.write(fos);
	     fos.close();//关闭文件输出流
		 
		 return ServerResponse.createBySuccessMessage("填充数据成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ServerResponse.createBySuccessMessage("修改excell成功");
	}
	
	private Object toPDF(Techchange techchange){
		try {
			return ExcellUtil.excel2Pdf(mainPath,techchange,"技改年报");
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage(e.getMessage());
		}
	}
	
	private void delMsg(User user){
		techchangeMapper.delMsg(user);
		techchangeMapper.updateVersion(user);
	}
	
	@Override
	public Object checkCommit(User user) {
		List<Techchange> techchangeLi=this.getMsgByAccount(user);
		if(techchangeLi.size()>0){
			
			for(int i=0;i<techchangeLi.size();i++){
				Techchange temp=techchangeLi.get(i);
				if(
						temp.getRecYear()==null||
						StringUtils.isBlank(temp.getUnitName())||
						StringUtils.isBlank(temp.getPrjName())||
						StringUtils.isBlank(temp.getUseType())||
						StringUtils.isBlank(temp.getPrjType())||
						StringUtils.isBlank(temp.getPrjPlace())||
						StringUtils.isBlank(temp.getStarTime())||
						StringUtils.isBlank(temp.getEndTime())||
						StringUtils.isBlank(temp.getPrjStatus())||
						temp.getSumFund()==null||
						temp.getOtherScale()==null||
						temp.getSumSave()==null||
						temp.getUnitHead()==null
						/*temp.getPrjType()==null||
				temp.getManagement()==null||
				temp.getUnitName()==null||
				temp.getPrjName()==null||
				temp.getSurfaceWater()==null||
				temp.getUseType()==null||
				temp.getStarTime()==null||
				temp.getEndTime()==null||
				temp.getPrjStatus()==null||
//				temp.getSubsidyFund()==null||
//				temp.getSelfFund()==null||
//				temp.getOtherFund()==null||
				temp.getSumFund()==null||
				temp.getOtherScale()==null||
//				temp.getReservoirVolume()==null||
//				temp.getBrickArea()==null||
//				temp.getGreenlandArea()==null||
				temp.getSumSave()==null
//				temp.getSupplyWater()==null||
//				temp.getSelfProvide()==null||
//				temp.getSurfaceWater()==null
						 */			  ){
					return ServerResponse.createByErrorMessage("技改年报内容尚未填写完成");
				}
			}
			return ServerResponse.createBySuccessMessage("技改年报内容填写完成");
		}else{
			return ServerResponse.createByErrorMessage("技改年报内容尚未填写完成");
		}
	}
	
	@Override
	public int getIfComit(User user) {
		return techchangeMapper.getIfComit(user);
	}

	@Override
	public int updateComit() {
		return techchangeMapper.updateComit();
	}

	@Override
	public Object bulidEmptyFile(String path, Techchange techchange, User user) {
		mainPath=path;
		List<Techchange> temp=new ArrayList<Techchange>();
		temp.add(techchange);
		//初始化excell成功
		ServerResponse cf=(ServerResponse)this.createFile(techchange);
		if(cf.getCode()==200){
			//
			ServerResponse sm=(ServerResponse)this.stuffMsg(temp,user);
			if(sm.getCode()==200){
				ServerResponse fn=(ServerResponse)this.toPDF(techchange);
					if(fn.getCode()==200){
						return ServerResponse.createBySuccessMessage("保存成功");
					}else{
						return fn;
					}
			}else{
				return sm;
			}
			
			}else{
				return ServerResponse.createByErrorMessage("数据库不存在记录");
			}
	}
}
